<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="用户名">
              <a-input v-model="queryParam.userName" placeholder="请输入"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="角色">
              <a-select v-model="queryParam.roleId" placeholder="请选择" allowClear>
                <a-select-option v-for="role in roleNames" :key="role.id" :value="role.id">{{ role.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24"></a-col>
          <a-col :md="6" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              <a-button type="danger" style="margin-left: 8px" @click="newAccount">新增</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <s-table
      ref="table"
      row-key="id"
      size="default"
      :columns="columns"
      :data="loadData"
    >
      <a-tag color="#108ee9" slot="roleName" slot-scope="text">{{ roleName(text) }}</a-tag>
      <a-tag :color="text === '1' ? 'blue' : text === '2' ? 'red' : 'pink'" slot="userStatus" slot-scope="text">{{ text | statusFilter }}</a-tag>
      <span slot="modifyTime" slot-scope="text">{{ text | moment }}</span>
      <span slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a href="javascript:;" @click="newPassword(record)">修改密码</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="delAccount(record)">删除</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>

    <a-modal
      :title="modal.title"
      style="top: 20px;"
      :width="800"
      v-model="modal.visible"
      @ok="handleOk"
      okText="保存"
      :confirmLoading="modal.loading"
      :maskClosable="false"
    >
      <a-form class="permission-form" :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          style="display: none"
        >
          <a-input
            v-decorator="['id']"
          />
        </a-form-item>
        <a-form-item
          v-if="modal.editType !== 2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="用户名"
        >
          <a-input
            placeholder="用户名"
            v-decorator="[
              'userName',
              {rules: [{ required: true, message: '请填写登录用账号' },
                       { max: 20, message:'用户名长度不能大于20个字符' }]}]"
          />
        </a-form-item>

        <a-form-item
          v-if="modal.editType === 2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="原密码"
          has-feedback
        >
          <a-input
            placeholder="原密码"
            v-decorator="[
              'oldPassword',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入原密码！',
                  },
                  {
                    max: 32,
                    message: '密码长度小于32个字符长度'
                  },
                  {
                    min: 6,
                    message: '密码长度必须大于6'
                  }
                ],
              },
            ]"
            type="password"
          />
        </a-form-item>

        <a-form-item
          v-if="modal.editType !== 1"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="modal.editType === 1 ? '新密码' : '密码'"
          has-feedback
        >
          <a-input
            :placeholder="modal.editType === 1 ? '新密码' : '密码'"
            v-decorator="[
              'password',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                  {
                    validator: validateToNextPassword,
                  },
                  {
                    min: 6,
                    message: '密码长度必须不小于6位'
                  },
                  {
                    max: 32,
                    message: '密码长度需要小于32位'
                  }
                ],
              },
            ]"
            type="password"
          />
        </a-form-item>

        <a-form-item
          v-if="modal.editType !== 1"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="确认密码"
          has-feedback
        >
          <a-input
            placeholder="密码"
            v-decorator="[
              'confirm',
              {
                rules: [
                  {
                    required: true,
                    message: '请确认你的密码！',
                  },
                  {
                    validator: compareToFirstPassword,
                  },
                ],
              },
            ]"
            type="password"
            @blur="handleConfirmBlur"
          />
        </a-form-item>

        <a-form-item
          v-if="modal.editType !== 2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="电话号码">
          <a-input
            v-decorator="[
              'phone',
              {
                rules: [{ required: true, message: '请输入手机号' },
                        { validator: telephoneValidator}],
              },
            ]"
          >
            <a-select
              slot="addonBefore"
              v-decorator="['prefix', { initialValue: '86' }]"
            >
              <a-select-option value="86">
                +86
              </a-select-option>
              <a-select-option value="87">
                +87
              </a-select-option>
            </a-select>
          </a-input>
        </a-form-item>

        <a-form-item
          v-if="modal.editType !== 2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="角色"
        >
          <a-select
            placeholder="角色"
            v-decorator="['roleId', {
              rules: [{
                required: true, message: '请选择角色！'
              }]
            }]"
          >
            <a-select-option v-for="role in roleNames" :key="role.id" :value="role.id">
              {{ role.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          v-if="modal.editType !== 2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态"
        >
          <a-select
            placeholder="状态"
            v-decorator="['userStatus', {
              rules: [{
                required: true, message: '请选择状态！'
              }]
            }]"
          >
            <a-select-option value="1">
              在职
            </a-select-option>
            <a-select-option value="2">
              离职
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          v-if="modal.editType !== 2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="部门"
        >
          <a-select
            placeholder="部门"
            v-decorator="['depId', {
              rules: [{
                required: true, message: '请选择状态！'
              }]
            }]"
          >
            <a-select-option v-for="dep in depNames" :key="dep.codeDetail" :value="dep.codeDetail">{{ dep.codeContent1 }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

  </a-card>
</template>

<script>
  import pick from 'lodash.pick'
  import { STable } from '@/components'
  import * as api from '../../api/systemAdmin'
  import { RoleNames } from '../../api/common'
  import moment from 'moment'
  import * as codeApi from '@/api/common'

  const STATUS = {
    1: '在职',
    2: '离职'
  }

  const columns = [
    {
      title: '用户名',
      dataIndex: 'userName'
    },
    {
      title: '角色名称',
      dataIndex: 'roleId',
      scopedSlots: { customRender: 'roleName' }
    },
    {
      title: '手机号',
      dataIndex: 'phone'
      // scopedSlots: { customRender: 'userStatus' }
    },
    {
      title: '创建时间',
      dataIndex: 'modifyTime',
      scopedSlots: { customRender: 'modifyTime' }
      // sorter: true
    }, {
      title: '操作',
      width: '150px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    }
  ]

  export default {
    name: 'Account',
    components: {
      STable
    },
    data () {
      return {
        modal: {
          title: '',
          visible: false,
          loading: false,
          editType: 0 // 0 新增状态， 1 编辑状态， 2 修改密码
        },
        confirmDirty: false,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        form: this.$form.createForm(this),
        permissions: [],

        // 查询参数
        queryParam: {},
        // 表头
        columns,
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return api.getAccountList(Object.assign(parameter, this.queryParam))
            .then(res => {
              console.log('getAccountList', res)
              return res.result
            })
        },

        // 角色下拉框
        roleNames: [],

        // 部门下拉框
        depNames: []
      }
    },
    computed: {
    },
    filters: {
      statusFilter (key) {
        return STATUS[key]
      },
      momentFilter (key) {
        return moment(key).format('YYYY-MM-DD HH:MM:SS')
      }
    },
    created () {
      RoleNames().then(res => {
        this.roleNames = res.result
        console.log('roleNames', this.roleNames)
      })
      codeApi.CodeDetail({ codeType: '1' }).then(res => {
        console.log('部门', res.result)
        this.depNames = res.result
      })
    },
    methods: {
      roleName (roleId) {
        return this.roleNames.filter(item => item.id === roleId)[0].name
      },
      newAccount () {
        this.modal.title = '新增用户'
        this.form.resetFields()
        this.modal.loading = false
        this.modal.editType = 0
        this.modal.visible = true
      },
      newPassword (record) {
        this.modal.title = '修改密码'
        this.form.resetFields()
        this.modal.loading = false
        this.modal.editType = 2
        this.modal.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, ['id']))
        })
      },
      handleEdit (record) {
        this.modal.title = '修改用户'
        this.modal.loading = false
        this.modal.editType = 1
        this.modal.visible = true
        console.log('record', record)

        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, ['id', 'userName', 'phone', 'roleId', 'userStatus', 'depId']))
        })
      },
      handleOk (e) {
        e.preventDefault()
        this.modal.loading = true
        if (this.modal.editType === 2) { // 修改密码
          this.form.validateFields((err, values) => {
            if (err == null) {
              setTimeout(() => {
                console.log(values)
                api.ChangePassword({
                  id: values.id,
                  oldPassword: values.oldPassword,
                  newPassword: values.password,
                  confirmPassword: values.confirm
                }).then(res => {
                  console.log(res)
                  if (res.code === 200) {
                    if (res.msg.indexOf('成功') >= 0) {
                      this.$message.success('修改成功！')
                      this.$refs.table.refresh(true)
                      this.modal.loading = false
                      this.modal.visible = false
                    } else {
                      this.$message.error('修改失败！' + res.msg)
                      this.modal.loading = false
                    }
                  } else {
                    this.$message.error('服务出错' + res.msg)
                    this.modal.loading = false
                  }
                }).catch(e => {
                  this.$message.error('修改失败！')
                  this.modal.loading = false
                  console.error(e)
                })
              }, 2000)
            } else {
              this.$message.error('存在非法输入！')
              setTimeout(() => {
                this.modal.loading = false
                this.$nextTick(() => {
                  this.modal.loading = false
                })
              }, 500)
            }
          })
        } else { // 新增&保存用户
          this.form.validateFields((err, values) => {
            if (err == null) {
              setTimeout(() => {
                delete values.confirm
                delete values.prefix
                console.log(values)
                api.SaveAccount(values).then(res => {
                  console.log(res)
                  if (res.code === 200) {
                    if (res.msg.indexOf('成功') >= 0) {
                      this.$message.success('保存成功！')
                      this.$refs.table.refresh(true)
                      this.modal.loading = false
                      this.modal.visible = false
                    } else {
                      this.$message.error('保存失败！' + res.msg)
                      this.modal.loading = false
                    }
                  } else {
                    this.$message.error('服务出错' + res.msg)
                    this.modal.loading = false
                  }
                }).catch(e => {
                  this.$message.error('保存失败！')
                  this.modal.loading = false
                  console.error(e)
                })
              }, 2000)
            } else {
              this.$message.error('存在非法输入！')
              setTimeout(() => {
                this.modal.loading = false
                this.$nextTick(() => {
                  this.modal.loading = false
                })
              }, 500)
            }
          })
        }
      },
      handleConfirmBlur (e) {
        const value = e.target.value
        this.confirmDirty = this.confirmDirty || !!value
      },
      compareToFirstPassword (rule, value, callback) {
        const form = this.form
        if (value && value !== form.getFieldValue('password')) {
          callback(new Error('两次密码不一致！'))
        } else {
          callback()
        }
      },
      validateToNextPassword (rule, value, callback) {
        const form = this.form
        if (value && this.confirmDirty) {
          form.validateFields(['confirm'], { force: true })
        }
        callback()
      },
      telephoneValidator (rule, value, callback) {
        if (value && !(/^1[3456789]\d{9}$/.test(value))) {
          callback(new Error('手机号格式错误！'))
        } else {
          callback()
        }
      },
      delAccount (record) {
        const _this = this
        this.$confirm({
          title: '确定删除该用户么',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk () {
            api.DelAccount({ id: record.id }).then(res => {
              if (res.code === 200) {
                if (res.msg.indexOf('成功') >= 0) {
                  _this.$message.success('删除成功！')
                  _this.$refs.table.refresh(true)
                } else {
                  _this.$message.error('删除失败！' + res.msg)
                }
              } else {
                _this.$message.error('服务出错' + res.msg)
              }
            })
          },
          onCancel () {
          }
        })
      }
    },
    watch: {
    }
  }
</script>

<style lang="less" scoped>
  .permission-form {
    /deep/ .permission-group {
      margin-top: 0;
      margin-bottom: 0;
    }
  }

</style>
